package handler

import (
	"context"
	"lab-service/account/model"
	pu "lab-service/proto/user"
)

type User struct{}

func (u *User) One(ctx context.Context, req *pu.UserRequest, rsp *pu.UserResponse) error {
	// model User -> mu
	mu := &model.User{
		Id: req.Uid,
	}

	if err := mu.OneById(); err != nil {
		return err
	}

	rsp.User = &pu.OneUser{
		Id:        mu.Id,
		UserName:  mu.UserName,
		Phone:     mu.Phone,
		Email:     mu.Email,
		Enable:    mu.Enable,
		CreatedAt: mu.CreatedAt.Unix(),
	}

	return nil
}

func (u *User) Page(ctx context.Context, req *pu.UserRequest, rsp *pu.UserResponse) error {
	// model User -> mu
	mu := &model.User{
		Enable: req.Enable,
	}

	us, err := mu.Page(req.PageNum, req.PageSize, req.Desc, req.Order)
	if err != nil {
		return err
	}

	for _, u := range us {
		rsp.Users = append(rsp.Users, &pu.OneUser{
			Id:        u.Id,
			CreatedAt: u.CreatedAt.Unix(),
			Enable:    u.Enable,
			Email:     u.Email,
			UserName:  u.UserName,
			Phone:     u.Phone,
		})
	}

	rsp.Total, err = mu.Count()
	if err != nil {
		return err
	}

	rsp.PageSize = req.PageSize
	rsp.PageNum = req.PageNum

	return nil
}

func (u *User) Login(ctx context.Context, req *pu.UserRequest, rsp *pu.UserResponse) error {
	// model User -> mu
	mu := &model.User{
		Id:       req.Uid,
		UserName: req.UserName,
		Email:    req.Email,
		Phone:    req.Phone,
	}
	if err := mu.Login(req.Password); err != nil {
		return err
	}

	rsp.Uid = mu.Id

	return nil
}

func (u *User) Register(ctx context.Context, req *pu.UserRequest, rsp *pu.UserResponse) error {
	// model User -> mu
	mu := &model.User{
		UserName: req.UserName,
		Email:    req.Email,
		Phone:    req.Phone,
		Enable:   true,
	}
	if err := mu.CheckUnique(); err != nil {
		return err
	}
	if err := mu.Create(req.Password); err != nil {
		return err
	}

	rsp.Uid = mu.Id

	return nil
}

func (u *User) ResetPass(ctx context.Context, req *pu.UserRequest, rsp *pu.UserResponse) error {
	// todo ResetPass
	return nil
}

func (u *User) ChangePass(ctx context.Context, req *pu.UserRequest, rsp *pu.UserResponse) error {
	// model User -> mu
	mu := &model.User{
		Id: req.Uid,
	}
	if err := mu.OneById(); err != nil {
		return err
	}

	if err := mu.ChangePass(req.Password); err != nil {
		return err
	}

	return nil
}
